<i18n>
{
  "en": {
    "page_title": "User Management",
    "input_search_placeholder": "Search",
    "btn_new": "New User",
    "col_username": "User",
    "col_name": "Name",
    "col_role_name": "Role",
    "col_dept": "Department",
    "col_create_time": "Create Time",
    "search_username": "Search User",
    "role_type": "Role Type",
    "select_role": "Select Roles",
    "area": "Area",
    "country": "Country"
  },
  "zh": {
    "page_title": "用户管理",
    "input_search_placeholder": "请输入用户名",
    "btn_new": "新增用户",
    "col_username": "用户名",
    "col_name": "姓名",
    "col_role_name": "角色名称",
    "col_dept": "所属部门",
    "col_create_time": "创建日期",
    "search_username": "搜索用户",
    "role_type": "权限类型",
    "select_role": "选择角色",
    "area": "区域",
    "country": "国家"
  }
}
</i18n>

<template>
<div>
  <div class="page-header">
    <el-row :gutter="10">

      <el-col :xs="4" :sm="4" :md="4" :lg="4" :xl="4">
        <div class="page-header__title">{{$t('page_title')}}</div>
      </el-col>

      <el-col :xs="20" :sm="20" :md="20" :lg="20" :xl="20" class="text-right">
        <el-form :inline="true" :model="searchForm">
          <el-form-item>
            <el-input :placeholder="$t('input_search_placeholder')" v-model="searchForm.username">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="getDataList()"></i>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-date-picker class="ml30" v-model="searchForm.dateRange" type="daterange"
              range-separator="~" :start-placeholder="$t('common.start_date')" :end-placeholder="$t('common.end_date')">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="getDataList">{{$t('common.search')}}</el-button>
            <el-button type="danger" @click="addOrUpdateHandle()">{{$t('btn_new')}}</el-button>
          </el-form-item>

        </el-form>
      </el-col>

    </el-row>
  </div>

  <el-card class="table-container">
    <el-table :data="dataList" style="width: 100%">
      <el-table-column type="index" width="60" :label="$t('common.col_index')">
      </el-table-column>
      <el-table-column prop="userName" :label="$t('工号')">
      </el-table-column>
      <el-table-column prop="showName" :label="$t('col_name')">
      </el-table-column>
      <el-table-column prop="roleName" :label="$t('col_role_name')">
      </el-table-column>
      <el-table-column prop="deptName" :label="$t('col_dept')">
      </el-table-column>
      <el-table-column prop="createTime" :label="$t('col_create_time')">
      </el-table-column>

      <el-table-column label-class-name="text-center" class-name="text-center action" prop="operate" :label="$t('common.operation')"
        width="180">
        <template slot-scope="scope">
          <a href="/" class="text-warning" @click.prevent="addOrUpdateHandle(scope.row)">{{$t('common.edit')}}</a>
          <a href="/" class="text-danger" @click.prevent="avaibleHandle(scope.row)">{{scope.row.status === 1 ? $t('common.disable') : $t('common.enable')}}</a>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize" layout="total, prev, pager, next, jumper"
      :total="totalPage"
      @current-change="onCurrentChange">
    </el-pagination>
  </el-card>

  <!--:title="'查看，新增，编辑-详情'"-->
  <el-dialog
    :key="dialogKey"
    :title="dialogTitle"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="onClose">
    <el-form
      ref="dataForm"
      label-width="120px"
      :model="current"
      :rules="dialogDataRules"
      :validate-on-rule-change="false"
      @keyup.enter.native.prevent="ok">
      <!-- <el-form-item :label="$t('search_username')" prop="name">
        <el-select
          v-model="current.name"
          filterable
          clearable
          remote
          placeholder="请输入关键词"
          :remote-method="getRemoteUsers"
          :loading="remoteUserloading">
          <el-option v-for="item in userListOptions"
            :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-input></el-input>
      </el-form-item> -->

      <el-form-item :label="$t('工号')" prop="userName">
        <el-input v-model="current.userName"></el-input>
      </el-form-item>

      <el-form-item :label="$t('部门编码')" prop="deptNo">
        <el-input v-model="current.deptNo"></el-input>
      </el-form-item>

      <el-form-item :label="$t('部门名称')" prop="deptName">
        <el-input v-model="current.deptName"></el-input>
      </el-form-item>
      <el-form-item :label="'中文名称'" prop="showName">
          <el-input v-model="current.showName"></el-input>
      </el-form-item>

      <el-form-item :label="'英文名称'" prop="showEnglishName">
          <el-input v-model="current.showEnglishName"></el-input>
      </el-form-item>

      <el-form-item :label="'邮箱'" prop="email">
          <el-input v-model="current.email"></el-input>
      </el-form-item>

      <el-form-item :label="'电话'" prop="mobile">
          <el-input v-model="current.mobile"></el-input>
      </el-form-item>

      <el-form-item :label="'用户类型'" prop="userType">
          <el-select v-model="current.userType" placeholder="请选择">
          <el-option
            v-for="item in userTpeList"
            :key="item.code"
            :label="item.cnName"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="'区域/国家'" prop="areaCountryCode" >
        <el-cascader 
          v-model="current.areaCountryCode" 
          :options="areaCodeList"
          :props="areaProps"
          placeholder="请选择">
  
        </el-cascader>
      </el-form-item> 

      <!-- <el-form-item :label="'产品线'" prop="productLine">
        <el-card>
          <CheckboxTree :data="treeData" v-model="current.productLine" @change="TreeDatachange" :key="$route.query.productDirectoryId" />
        </el-card>
      </el-form-item> -->
      <el-form-item :label="$t('select_role')" prop="roleIdList">
        <el-checkbox-group v-model="roleIdList">
          <el-checkbox 
            v-for="role in rolesJS" 
            :key="role.roleId"
            :label="role.roleId">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click.prevent="ok">{{$t('common.ok')}}</el-button>
      <el-button type="danger" @click="visible = false">{{$t('common.cancel')}}</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  import CheckboxTree from '@/components/checkboxTree'
  // const mockRoleOptions = ['总监', '研发经理', '运营专员', '开发']
  const mockUserList = ["Joe", "Alaska", "Arizona",
        "Arkansas", "California", "Colorado",
        "Connecticut", "Delaware", "Florida",
        "Georgia", "Hawaii", "Idaho", "Illinois",
        "Indiana", "Iowa", "Kansas", "Kentucky",
        "Louisiana", "Maine", "Maryland",
        "Massachusetts", "Michigan", "Minnesota",
        "Mississippi", "Missouri", "Montana",
        "Nebraska", "Nevada", "New Hampshire",
        "New Jersey", "New Mexico", "New York",
        "North Carolina", "North Dakota", "Ohio",
        "Oklahoma", "Oregon", "Pennsylvania",
        "Rhode Island", "South Carolina",
        "South Dakota", "Tennessee", "Texas",
        "Utah", "Vermont", "Virginia",
        "Washington", "West Virginia", "Wisconsin",
        "Wyoming"]


        let mockProductLineData = [{
          label: '一级产品线1',
          id: '1',
          disabled: true,
          children: [{
            id: '1-1',
            label: '二级产品线A',
          },{
            id: '1-2',
            label: '二级产品线B',
          }]
        }, {
          id: '2',
          label: '一级产品线2',
          disabled: true,
          children: [{
            id: '2-1',
            label: '二级产品线C'
          }, {
            id: '2-2',
            label: '二级产品线D'
          }]
        }
        ];

        let mockAreaCountryData = [{
          value: 'headerQuarter',
          label: '总部',
          children: [{
            value: 'cn',
            label: '中国',

          }, {
            value: 'in',
            label: '硬度',

          }]
        },
        {
          value: 'zujian',
          label: '区域',
          children: [{
            value: 'basic',
            label: 'Basic',

          }, {
            value: 'form',
            label: 'Form',

          }]
        }]


  export default {
    data () {
      return {
        // 用于重置表单
        dialogKey: Date.now(),

        // productLineData:mockProductLineData,

        selectedOptions: [],

        // 查询表单
        searchForm: {
          username: '',
          dateRange: '',
        },

        // 表格加载状态
        dataListLoading: false,
        // 表格数据
        dataList: [],
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,

        // 远程用户
        remoteUserloading: false,
        remoteUserList: [],
        userListOptions: [],

        //区域国家
        areaCodeList: [],
        areaProps: {
          value: 'code',
          // label: 'label',
          children: 'childList'
        },

        // 角色列表
        rolesJS: [],
        roleIdList: [],
        // 用户类型
        userTpeList: [],

        // 产品线
        treeData: [],

        // 执行的动作
        action: '',

        // 当前选择的行数据
        current: {
          userName: '', //工号
          deptNo: '', //部门编码
          deptName: '', //部门名称         
          // name: '',
          showName: '', //中文名称
          showEnglishName: '', //英文名称
          email: '', //邮箱
          mobile: '', //电话
          userType: '', //用户类型
          areaCountryCode: [],
          productLine: [],
          // role_type: '',
          roleIdList: []
        },

        // 控制弹窗的显示隐藏
        visible: false,

        // 添加/修改数据规则
        dataRule: {
          userName: [
            { required: true, message: '工号不能为空', trigger: 'blur' }
          ],
          deptNo: [
            { required: true, message: '部门编码不能为空', trigger: 'blur' }
          ],
          deptName: [
            { required: true, message: '部门名称不能为空', trigger: 'blur' }
          ],
          /* name: [
            { required: true, message: '请选择用户', trigger: 'change' }
          ], */
          showName: [
            { required: true, message: '中文名称不能为空', trigger: 'change' }
          ],
          showEnglishName: [
            { required: true, message: '英文名称不能为空', trigger: 'change' }
          ],
          email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '电话不能为空', trigger: 'blur' }
          ],
          userType: [
            { required: true, message: '用户类型', trigger: 'change' }
          ],
          areaCountryCode: [
            { required: true, message: '请选择国家区域', trigger: 'change' }
          ],
          productLine: [
            { required: true, message: '请选择产品线', trigger: 'change' }
          ],
          /* role_type: [
            { required: true, message: '请选择权限类型', trigger: 'change' }
          ], */
          /* roleIdList: [
            { required: true, message: '请选择相应角色', trigger: 'change' }
          ] */
        },

      }
    },
    components: {
      CheckboxTree
    },
    created () {
      this.getDataList()

      /* 新增用户 区域/国家 */
      this.areaCode()

      /* 新增用户 用户类型 */
      this.userType()
      /* 新增用户 产品线获取 */
      // this.getProductLines()

      /* 角色新增 默认请求 */
        this.deafultRoles()

      // TODO: get remote Users
      this.remoteUserList = mockUserList.map(item => {
        return { value: item, label: item };
      });
      // TODO: get User Roles
      // this.roles = mockRoleOptions;
    },
    computed: {
      dialogTitle() {
        return this.action === 'view' ? this.$t('common.view_dialog_title'): (!this.current.id ? this.$t('common.new_dialog_title') : this.$t('common.edit_dialog_title'))
      },
      dialogDataRules() {
        return this.action === 'view'? {} : this.dataRule
      }
    },
    methods: {

      // 区域国家
      areaCode(){
         this.$http({
          url: this.$http.adornUrl('/prm-os-srv-sys/api/sysArea/queryAllAreaAndCountryTree'),
          method: 'post',
          data: this.$http.adornParams({})
        }).then((data) => {
            this.areaCodeList= data.data
        })
      },

      //用户类型
      userType() {
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-sys/sys/cpqsystemconfig/querySystemConfigByType'),
          method: 'post',
          data: this.$http.adornParams({
            "type": "User_Type"
          })
        }).then( data => {
          this.userTpeList = data.cpqSystemConfig
        })
      },

      // 获取产品线树
      getProductLines () {
        this.dataLoading = true
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-prod/queryProductInformationLineList'),
          method: 'post',
          data: this.$http.adornParams()
        }).then(data => {
          if (data && data.code === 0) {
            let _data = data.data || {}
            let treeData = _data.productInformationList || [];

            this.treeData = treeData
          }

          this.dataLoading = false
        })
      },

      // 选择角色 默认数据
      deafultRoles() {
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-sys/sys/user/queryRoleList'),
          method: 'post',
          data: this.$http.adornParams()
        }).then( data => {
          this.rolesJS = data.data
        })
      },

      getRemoteUsers(query) {
        if (query !== '') {
          this.remoteUserloading = true;
          // TODO: 远程加载用户列表
          setTimeout(() => {
            this.remoteUserloading = false;
            this.userListOptions = this.remoteUserList.filter(item => {
              return item.label.toLowerCase()
                .indexOf(query.toLowerCase()) > -1;
            });
          }, 200);
        } else {
          this.userListOptions = [];
        }
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-sys/sys/user/queryUserList'),
          method: 'post',
          data: this.$http.adornParams({
            'pageNo': this.currentPage - 1,
            'pageSize': this.pageSize,
            'userName': this.searchForm.username,
            'dateRange': this.searchForm.dateRange
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.dataList = data.data.list
            this.totalPage = data.dta.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },

      /* 产品线选择 */
      TreeDatachange(data) {

      },
      /**
       * 每页显示条数改变
       */
      onSizeChange (pageSize) {
        this.currentPage = 1
        this.pageSize = pageSize
        this.getDataList()
      },
      /**
       * 当前页码改变
       */
      onCurrentChange (currentPage) {
        this.currentPage = currentPage
        this.getDataList()
      },
      // 新增 / 修改
      addOrUpdateHandle (rowData) {
        this.visible = true
        this.action = 'edit'
        this.current = rowData || { name: '', role_type: '', roles: []}
      },
      //  弹窗关闭清除上次的校验结果
      onClose () {
        this.dialogKey = Date.now();
        // this.$refs['dataForm'].clearValidate()
      },

      // 点击确认
      ok () {

        // 编辑操作
        if (this.action === 'edit') {
          return this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              this.current.roleIdList = this.roleIdList
              this.$http({
                url: this.$http.adornUrl("/prm-os-srv-sys/sys/user/save"),
                method: 'post',
                data: this.$http.adornData(this.current)
              }).then((data) => {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.getDataList()
                    }
                  })
               
              })
            }
          })
        } else {
          this.visible = false
        }
      },
      // 启用、停用
      avaibleHandle (rowData) {
        let updatingStatus = rowData.status === 1 ? 0 : 1;
        let updatingStatusText = rowData.status === 1 ? "停用" : "启用";
        this
          .$confirm(`确定${updatingStatusText}该用户吗?`, '提示', {
            type: 'warning'
          })
          .then(() => {
            return this.$http({
              url: this.$http.adornUrl('/product/cpqsystemuser/change_status'),
              method: 'post',
              data: this.$http.adornData({
                'id': rowData.id,
                'status': updatingStatus
              })
            })
          })
          .then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
          .catch(() => {})
      },

    }
  }
</script>


<style lang="scss" scoped>

  .ml30 {
    margin-left: 30px;
  }
  .areaCode{
    display: flex;
    justify-content: space-between;
  }

</style>
